﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace BaccaratRally.DataKernel.Service
{
    public class ServiceBase
    {
        /// <summary>
        /// 从SqlDataReader中取出值
        /// </summary>
        /// <typeparam name="T">取值的泛型类别</typeparam>
        /// <param name="reader">SqlDataReader</param>
        /// <param name="field">数据字段</param>
        /// <returns>取值的泛型类别</returns>
        protected internal T GetReaderValue<T>(SqlDataReader reader, string field)
        {
            T result = default(T);
            int pos = reader.GetOrdinal(field);
            if (pos < 0)
                return result;
            if (reader.IsDBNull(pos))
                return result;

            try
            {
                result = (T)Convert.ChangeType(reader.GetValue(pos), typeof(T));
            }
            catch (InvalidCastException ex)
            {
            }
            catch
            {
                throw;
            }

            return result;
        }

        /// <summary>
        /// 从DataRow中取出值
        /// </summary>
        /// <typeparam name="T">取值的泛型类别</typeparam>
        /// <param name="dataRow">DataRow</param>
        /// <param name="field">数据字段</param>
        /// <returns>取值的泛型类别</returns>
        protected internal T GetDataRowValue<T>(DataRow dataRow, string field)
        {
            T result = default(T);

            if (dataRow.IsNull(field))
                return result;

            try
            {
                result = (T)Convert.ChangeType(dataRow[field], typeof(T));
            }
            catch (InvalidCastException ex)
            {
            }
            catch
            {
                throw;
            }

            return result;
        }
    }
}
